using ModelContextProtocol.AspNetCore;
using ModelContextProtocol.Server; 
using System.Reflection;
using WeatherAlertMcp.Api.Tools; 

namespace WeatherAlertMcp.Api
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            // Add services to the container.
            builder.Services.AddControllers();
            builder.Services.AddEndpointsApiExplorer();
            builder.Services.AddSwaggerGen();

            // 开发期 CORS（允许跨域调用）
            builder.Services.AddCors(options =>
            {
                options.AddPolicy("DevCors", policy =>
                    policy.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
            });

            // MCP: 注册 HttpClient 与 MCP 服务器，并从当前程序集扫描工具
            builder.Services.AddHttpClient();
            builder.Services.AddMemoryCache(); // 缓存
            builder.Services.AddTransient<WeatherTool>(); // 注册工具到 DI，供 REST 端点使用
            builder.Services
                .AddMcpServer()
                .WithHttpTransport()
                .WithToolsFromAssembly(typeof(Program).Assembly);

            var app = builder.Build();

            if (app.Environment.IsDevelopment())
            {
                app.UseSwagger();
                app.UseSwaggerUI();
            }

            app.UseCors("DevCors");
            app.UseAuthorization();

            app.MapControllers();

            // 对前端暴露的 REST 端点（基于 WeatherTool）
            app.MapGet("/api/weather/forecast", async (double lat, double lon, WeatherTool tool) =>
            {
                return Results.Ok(await tool.GetForecastAsync(lat, lon));
            });

            app.MapGet("/api/weather/forecast-by-address", async (string address, WeatherTool tool) =>
            {
                return Results.Ok(await tool.GetForecastByAddressAsync(address));
            });

            // MCP: 映射 SSE 端点
            app.MapMcp();

            app.Run();
        }
    }
}
